// index.js
// 获取应用实例
const app = getApp()
const authBehavior = require('../../behavior/auth-behavior')

Page({
    behaviors: [authBehavior],
    data: {
        viewUrl: app.globalData.viewUrl,
        adList: [],
        cateList: [],
        menuList: [],
        // 当前scroll-view所处位置
        toView: '',
        // 当前活动分类
        activeIdx: 0,
        heightList: [],
        loading: false
    },
    // 事件处理函数
    bindViewTap() {
    },
    onLoad() {
        this.getAdList()
        this.getSessionInfo();
    },
    async onShow() {
        await this.fecthData();
        await this.showAuthDialog();
    },
    onUnload() {
        // wx.clearStorageSync()
    },
    /**
     * 处理菜单
     * 将分类和商品处理成树形格式
     */
    async fecthData() {
        this.setData({ loading: true })
        // 获取分类列表
        const { data: cateList } = await app.requestAll({
            url: 'category/selectList'
        })
        // 获取商品列表
        const { data: productList } = await app.requestAll({
            url: 'product/selectList'
        })
        const cartList = await this.getCartList()
        // 将分类和商品列表合并成children形式
        const treeMap = {}
        const result = []
        for (let i = 0; i < cateList.length; i++) {
            const element = cateList[i];
            treeMap[element.id] = {
                ...element,
                children: []
            }
            result.push(treeMap[element.id])
        }
        for (let i = 0; i < productList.length; i++) {
            const element = productList[i];
            if (treeMap[element.cateId]) {
                const item = cartList.find(e => e.productId === element.id)
                treeMap[element.cateId].children.push({ ...element, number: item ? item.number : 0 })
            }
        }
        // 获取每个商品分类的高度区域
        const heightList = [0]
        let height = 0
        for (let i = 0; i < result.length - 1; i++) {
            const ele = result[i];
            height += (56 + ele.children.length * 104)
            heightList.push(height)
        }
        this.setData({
            cateList,
            menuList: result,
            heightList,
            loading: false
        })
    },
    /**
     * 获取广告图数据
     */
    async getAdList() {
        if (!this.showAuthDialog()) return []
        const { data } = await app.requestAll({
            url: 'advertise/selectList',
            alert: false,
            params: { status: 1 }
        })
        this.setData({
            adList: data || []
        })
    },
    /**
     * 获取购物车数据
     */
    async getCartList() {
        if (!this.showAuthDialog()) return []
        const { data } = await app.requestAll({
            url: 'cart/selectListByUser',
            alert: false
        })
        this.setData({
            cartList: data || []
        })
        return data || []
    },
    /**
     * 点击左侧导航栏事件
     * @param {*} e 
     */
    onClickNav(e) {
        const dataset = Object.keys(e.target.dataset).length ? e.target.dataset : e.currentTarget.dataset
        if (typeof dataset.index !== "number") return
        this.setData({
            activeIdx: dataset.index
        })
        this.setData({
            toView: "p-" + dataset.id
        })
    },
    /**
     * 右侧商品区滑动事件
     * @param {*} e 
     */
    scroll(e) {
        for (let i = 0; i < this.data.heightList.length; i++) {
            let height1 = this.data.heightList[i]
            let height2 = this.data.heightList[i + 1] || 1000000
            if (e.detail.scrollTop >= height1 && e.detail.scrollTop < height2 && this.data.activeIdx !== i) {
                return this.setData({
                    activeIdx: i
                })
            }
        }
    },
    /**
     * 更新购物车数据
     * 增删改
     * @param {*} e 
     */
    async updateCart(e) {
        if (!this.showAuthDialog()) return;
        const dataset = Object.keys(e.target.dataset).length ? e.target.dataset : e.currentTarget.dataset
        console.log(dataset);
        const list = this.data.menuList
        let number = list[dataset.menuidx].children[dataset.index].number
        if (number == 0) {
            list[dataset.menuidx].children[dataset.index].number = number + 1
        } else {
            list[dataset.menuidx].children[dataset.index].number = e.detail
        }
        await this.setData({
            menuList: list
        })
        const { data } = await app.requestAll({
            url: 'cart/updateCartByUser',
            method: "POST",
            params: {
                productId: dataset.row.id,
                number: list[dataset.menuidx].children[dataset.index].number,
            },
            alert: false
        })
    },
    toCartPage() {
        if (!this.showAuthDialog()) return
        wx.navigateTo({
            url: '/pages/cart/index',
        })
    },
})
